import React, { Component } from 'react'
import { updateRecord, deleteRecord } from '../utils/Config';

export default class Record extends Component {

  constructor(props) {
    super(props);
    this.state = {
      time: null,
      edit: false
    }
  }
  

  transformTimer (ms) {
    return new Date(ms*1000).Format("yyyy-MM-DD")
  }

  handleEdit () {
    this.setState({
      edit: !this.state.edit
    });
  }

  handleUpdate () {
    const record = {
      date: Number.parseInt(this.refs.date.value,0),
      title: this.refs.title.value,
      amount: Number.parseInt(this.refs.amount.value,0)
    }
    // 上传服务器
    updateRecord(this.props.record.id,record).then(
      response => {
        this.props.handleUpdateRecord(this.props.record,response.data)
        this.handleEdit()
      }
    ).catch(
      error => console.log(error.message)
    );
  }

  handleDelete () {
    deleteRecord(this.props.record.id).then(
      response=>{
        this.props.handleDeleteRecord(this.props.record);
      }
    ).catch(
      error=> console.log(error.message)
    );
  }

  recordRow () {
    return (
      <tr>
        <td>{this.props.record.date}</td>
        <td>{this.props.record.title}</td>
        <td>{this.props.record.amount}</td>
        <td>
          <button className="btn btn-info mr-1" onClick={this.handleEdit.bind(this)}>编辑</button>
          <button className="btn btn-danger mr-1" onClick={this.handleDelete.bind(this)}>删除</button>
        </td>
      </tr>
    )
  }

  recordForm() {
    return (
      <tr>
        <td>
          <input type="text" defaultValue={this.props.record.date} ref="date"/>
        </td>
        <td>
          <input type="text" defaultValue={this.props.record.title} ref="title"/>
        </td>
        <td>
          <input type="text" defaultValue={this.props.record.amount} ref="amount"/>
        </td>
        <td>
          <button className="btn btn-info mr-1" onClick={this.handleUpdate.bind(this)}>更新</button>
          <button className="btn btn-danger mr-1" onClick={this.handleEdit.bind(this)}>取消</button>
        </td>
      </tr>
    )
  }

  render() {
    if (this.state.edit) {
      return this.recordForm();
    }else{
      return this.recordRow();
    }
    
  }
}